package com.admin.scroller.photoorvideo.tasks;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.admin.scroller.photoorvideo.callback.OnSavePhoto;

import java.io.File;
import java.io.FileOutputStream;

public class BitmapSaveTask extends AsyncTask<Bitmap,Void,String> {

    private OnSavePhoto onSavePhoto;

    public BitmapSaveTask(OnSavePhoto onSavePhoto){
        this.onSavePhoto=onSavePhoto;
    }

    @Override
    protected String doInBackground(Bitmap... bitmaps) {
        String root=Environment.getExternalStorageDirectory().getPath();
        File file=new File(root+"/photovideo",System.currentTimeMillis()+".jpeg");
        try{
            if(!file.exists()){
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            FileOutputStream outputStream=new FileOutputStream(file);
            bitmaps[0].compress(Bitmap.CompressFormat.JPEG,100,outputStream);
            outputStream.flush();
            outputStream.close();
            return file.getPath();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        if(onSavePhoto!=null){
            if(!TextUtils.isEmpty(s)){
                onSavePhoto.onSuccess(s);
            }else {
                onSavePhoto.onError("保存失败");
            }
        }

    }
}
